package org.malred
package lecture.part1basics

object Functions extends App {
  //  def aFn(a: String, b: Int) = { // 可以不写返回值
  def aFn(a: String, b: Int): String = {
    a + " " + b
  }

  println(aFn("hello", 100))

  def aParameterlessFn(): Int = 42

  println(aParameterlessFn()) // 42
  println(aParameterlessFn) // 42

  // WHEN YOU NEED LOOPS, USE RECURSION.
  def aRepeatedFn(aStr: String, n: Int): String = {
    if (n == 1) aStr
    else aStr + aRepeatedFn(aStr, n - 1)
  }

  println(aRepeatedFn("hello", 3)) // hellohellohello

  def aFnWithSideEffects(aStr: String): Unit = println(aStr)

  def aBigFn(n: Int): Int = {
    def aSmallFn(a: Int, b: Int): Int = a + b

    aSmallFn(n, n - 1)
  }

  println(aBigFn(5))

  /*
  1.A greeting function (name,age)=>"Hi,my name is Sname and I am sage years old."
  2.Factorial function 1 2 *3 *.*n
  3.A Fibonacci function
    f(1)=1
    f(2)=1
    f(n)=f(n-1)+f(n-2)
  4.Tests if a number is prime.
  */

  def greeting(name: String, age: Int) =
    println("Hi,my name is " + name + " and I am " + age + " years old.")

  greeting("java", 18)

  def factorial(n: Int): Int =
    if (n <= 0) 1
    else n * factorial(n - 1)

  println(factorial(5)) // 120

  def fibonacci(n: Int): Int =
    if (n <= 2) 1
    else fibonacci(n - 1) + fibonacci(n - 2)

  // 1 1 2 3 5 8 13 21
  println(fibonacci(8))

  def isPrime(n: Int): Boolean = {
    def isPrimeUtil(t: Int): Boolean =
      if (t <= 1) true
      else n % t != 0 && isPrimeUtil(t - 1)

    isPrimeUtil(n / 2)
  }

  println(isPrime(37))
  println(isPrime(2003))
  println(37 * 17)
}
